import React from 'react'
import path from 'path'
import express from 'express'
import routes from '../Routes'
import { StaticRouter, Route } from 'react-router-dom'
import { matchRoutes, renderRoutes } from 'react-router-config'
import { renderToString} from 'react-dom/server' 
import { Provider } from 'react-redux'
import {getStore} from '../store/index.js'
import proxy from 'express-http-proxy'
import axios from 'axios'

const app = express()
app.use(express.static('public'))

app.get('/static/api/js/share.js', function(req, res) {
	axios.get('http://bdimg.share.baidu.com' + req.url).then(function(data) {
		res.send(data.data)
	})
})

// 当访问data开头的url的时候，代理到localhost:8000去
// app.use('/front', proxy('http://39.108.141.176:8081', {
//   proxyReqPathResolver: function (req) {
//   	return '/front' + req.url
//   }
// }));

app.use('/front', proxy('http://localhost:8081', {
  proxyReqPathResolver: function (req) {
  	return '/front' + req.url
  }
}));

app.get('*', function(req, res) {
	const store = getStore(req)
	// store里面填充什么，我们不知道，需要根据路由来判断加载什么数据
	const matchedRoutes = matchRoutes(routes, req.path)
	// 根据路由的路径，来往store里面加数据
	
	const promises = []
	matchedRoutes.forEach(item => {
		if(item.route.loadData) {
			const promise = new Promise((resolve, reject) => {
				item.route.loadData(store, req).then(resolve).catch(resolve)
			})
			promises.push(promise)
		}
	})
	const context = {css: []}
	// 让matchRoutes里面所有的组件，对应的loadData都执行一遍
	Promise.all(promises).then(() => {
		const content = renderToString((
	    <Provider store={store}>
	      <StaticRouter location={req.path} context={context}>
	        <div>
	          { renderRoutes(routes) }
	        </div>
	      </StaticRouter>
	    </Provider>
	  ))
	  
	  if(context.NotFound) {
			res.status(404)
	  }else if(context.action === 'REPLACE') {
	  	res.redirect(301, context.url)
	  }


	  const cssStr = context.css.length ? context.css.join('\n') : ''

		res.send(`
			<html>
				<head>
					<title>Finnwu-个人博客</title>
					<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0,user-scalable=no">
					<style>${cssStr}</style>
				</head>
				<body>
					<div id="root">${content}</div>
					<script>
	          window.context = {
	            state: ${JSON.stringify(store.getState())}
	          }
	        </script>
					<script type="text/javascript" src="https://unpkg.com/wangeditor@3.1.1/release/wangEditor.min.js"></script>
					<script src="/index.js"></script>
				</body>
			</html>
		`)
	})

})

const server = app.listen(3000)